import gameSigeDesc from "./gameSigeDesc";
import httpUtils from "./XmlHttpTool";
import allVariableJs from "./allVariable";
import PlatformUtil from "./PlatformUtil";
import NumberView from "./NumberView";

cc.Class({

    extends: cc.Component,
    properties: {
       
        holeArray:[cc.Node],
        stopButton:cc.Button,
        chuiziBtn:cc.Node,
        timeshow:cc.Node,
        stopView:cc.Node,
        hurtsprites:cc.Node,
        gameSigeDescJs:gameSigeDesc,
        showChuziLocation:cc.Object,
        isClickChuzi:cc.Boolean,
        upTimes:cc.Integer,
        downTimes:cc.Integer,
        stayTimes:cc.Integer,
        allKindArray:[],
        mouseArray:[],
        allMouseArray:[],
        isDalyBool:cc.Boolean,
        next_time:cc.Integer,
        grade: 2,
        homeholeArray:[],//有地鼠的洞口
        allHoleArrays:[],//所有地鼠洞口
        otherArray:[],
        lastAllmouse:0,
        spinChuiziNode:cc.Node,
        isAddMouseDelay:cc.Boolean,
        gradeSecondDic:null,
        gradeThreeDic:null,
        gradeFourDic:null,
        SvprogressPrefab: cc.Prefab,
        timeBtn:cc.Node,
        isAddLevetwo:cc.Boolean,
        isAddLevethree:cc.Boolean,
        isAddLevefour:cc.Boolean,
        isIphoneX:cc.Boolean,
        isUseHammer:cc.Boolean,
        showHubProjess:cc.Node,
        backgroundImage:cc.Node,
        numberCompontent:NumberView,
        energyCompontent:NumberView,
        hammerLineTime:cc.Integer,
        topsprite:cc.Node,
        hammerSound:{
          default: null,
          type: cc.AudioClip
        },
        readyImage:cc.Node,
        goImage:cc.Node,
        hammerUserTime:cc.Node,
        readySound:{
          default: null,
          type: cc.AudioClip
        },
        goSound:{
          default: null,
          type: cc.AudioClip
        },
        isExmouseDell:cc.Boolean
  
      },
     

     
    refreCoinClick:function(){

    //   var that= this
    //  httpUtils.NhttpPost("/users/stars",{},function(res){

     
    //   var stars =parseInt(res["stars"])
    //   allVariableJs.starNumber=stars
    //   that.numberCompontent.setText(allVariableJs.starNumber)

    //  },function(failres){
    //   console.log('刷新金币错误',failres)
    //  }
    //  )
    },


    onLoad () {
      
    console.log("场景初始化成功",PlatformUtil.platform.params)
    allVariableJs.isEnterEndTimes=false
    sdkbox.PluginAdColony.init();
    this.spinChuiziNode=cc.find("Canvas/spinChuizi");
    this.isDalyBool=true
    this.isUseHammer=true
    this.isAddMouseDelay=true
    this.isClickChuzi=false
    this.isStartgame=true
    this.node.on('touchstart', function(event){
    this.showChuziLocation=event.getLocation()
    this.chuiziGetpointClick(this.showChuziLocation)

   }, this);

   allVariableJs.isUseHammer=false
     
  },

  startGameClick:function(){

      this.current = cc.audioEngine.play(this.readySound, false, 1);

      this.readyImage.active=true

      var changebig = cc.scaleTo(0.2,1.2);

      var changesmaill=cc.scaleTo(0.2,1.0)

      var  delayAction=cc.delayTime(0.5);

      var _this=this
      var  readyfinsh=cc.callFunc(function(){
          
        _this.readyImage.active=false
         
        _this.goImage.active=true

        _this.current = cc.audioEngine.play(_this.goSound, false, 1);

          var gobigAction=cc.scaleTo(0.2,1.2)

          var gosmallAction=cc.scaleTo(0.2,1.0)

          var  godelayAction=cc.delayTime(0.5);

          var _this2=_this
          
          var gofinsh=cc.callFunc(function(){

            _this2.goImage.active=false
            console.log("go执行完动画");
          })
      
          var goseq = cc.sequence(gobigAction,gosmallAction,godelayAction,gofinsh)

          _this.goImage.runAction(goseq)

      })
  
      var seq = cc.sequence(changebig,changesmaill,delayAction,readyfinsh)
  
      this.readyImage.runAction(seq)


      var that =this

      httpUtils.httpPost("/marmot/catch", {},function(res){

        console.log("开始游戏成功",JSON.stringify(res))
       
       that.getUserInfoMessage()

       allVariableJs.waterMouseNsArray.splice(0, allVariableJs.waterMouseNsArray.length);//清空数组 
  
       allVariableJs.waterMouseNsArray=[]

       that.upTimes=res["difficulty"]["grade_1"]["marmot_time"]["up"]
  
       that.downTimes=res["difficulty"]["grade_1"]["marmot_time"]["down"]
  
       that.stayTimes=res["difficulty"]["grade_1"]["marmot_time"]["on"]
  
       allVariableJs.starNumber=parseInt(res["stars"])

       that.numberCompontent.setText(allVariableJs.starNumber)
  
       that.hammerLineTime=parseInt(res["toolSecond"])
  
       allVariableJs.wawaCoinAddNumber=0

       allVariableJs.isPlaying=true

       allVariableJs.gameId=parseInt(res["game_id"])
  
       allVariableJs.chuiziCount=parseInt(res["hammerCount"])
  
       allVariableJs.timeCount=parseInt(res["timeCount"])
           
       that.chuiziBtn.getChildByName("hammerPropShow").getChildByName("hammerPropLabel").getComponent("NumberView").setText(allVariableJs.chuiziCount)
  
       that.timeBtn.getChildByName("timePropShow").getChildByName("timePropLabel").getComponent("NumberView").setText(allVariableJs.timeCount)
      //  res["game_time"]
       that.timeshow.getComponent("timeShow").init(res["game_time"])
  
       that.allKindArray=res["difficulty"]["grade_1"]["marmot_num"]


        console.log("请求结果", res);
  
       that.gradeSecondDic=res["difficulty"]["grade_2"]
  
       that.gradeThreeDic=res["difficulty"]["grade_3"]
  
       that.gradeFourDic=res["difficulty"]["grade_4"]
  
       that.lastAllmouse=that.allKindArray.length
  
       that.next_time=res["difficulty"]["grade_1"]["next_time"]
  
       that.isAddLevetwo=true
  
       that.isAddLevethree=true
  
       that.isAddLevefour=true
  
       var  allHoleArray=[]
  
       for(var i=0;i<24;i++){
  
            allHoleArray.push(i)
  
       }
  
      that.allHoleArrays=allHoleArray
  
      var  sortHoleArray=that.getRandomArrayElements(allHoleArray,that.lastAllmouse)
  
      var j=0
      for (var i = 0; i <sortHoleArray.length; i++) {
  
        setTimeout(function() {
  
            that.changeMouseLocation(sortHoleArray[j],j);
  
          j=j+1
         
        }, that.next_time*1000*i);
      
      }
  
    }
  
    ,function(failres){
  
      console.log("请求失败",failres)
  
      var item = cc.instantiate(that.SvprogressPrefab);
      that.node.addChild(item);
      item.getComponent('SVProgressView').init(failres.errdesc)
  
      let finish = cc.callFunc(() => { 
        
        item.destroy();
      
      }, that);
  
      let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(1.5), cc.fadeOut(1), finish);
      item.runAction(action);
  
     });
           
  },



   chuiziGetpointClick:function(location){
 
    if(this.isClickChuzi==false){

      // console.log("点击锤子的坐标",location)

    }else{

      if(allVariableJs.SourceChange==false){
        this.current = cc.audioEngine.play(this.hammerSound, false, 1);
      }

      this.spinChuiziNode.getComponent("spinChuizi").init()
      if(this.isIphoneX){
        this.spinChuiziNode.x=location.x-385;
        this.spinChuiziNode.y=location.y-812;
      }else{
        this.spinChuiziNode.x=location.x-375;
        this.spinChuiziNode.y=location.y-667-45;
      }
      console.log("点击锤子的坐标",location)

    }
   },

  //随机数组随机取几个数
  getRandomArrayElements: function(arr, count) {
    var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }

    return shuffled.slice(min); 
},

   gradeSecond:function(){

    console.log("第二等级",this.gradeSecondDic)
    if(this.isAddLevetwo){
      this.difficultyGrade(this.gradeSecondDic)
      this.isAddLevetwo=false
    }else{
      console.log("第二等级已经增加过了")
    }

   },

   gradeThree:function(){

   console.log("第三等级",this.gradeThreeDic)
   if(this.isAddLevethree){
    this.difficultyGrade(this.gradeThreeDic)
    this.isAddLevethree=false
   }else{
    console.log("第三等级已经增加过了")
   }
   },

   gradeFour:function(){

    console.log("第四等级",this.gradeFourDic)
    if(this.isAddLevefour){
      this.difficultyGrade(this.gradeFourDic)
      this.isAddLevefour=false
    }else{
      console.log("第四等级已经增加过了")
    }
   },

   difficultyGrade:function(gradedic){

    if(this.otherArray.length>2){

      this.upTimes=gradedic["marmot_time"]["up"]

      this.downTimes=gradedic["marmot_time"]["down"]

      this.stayTimes=gradedic["marmot_time"]["on"]

      this.next_time=gradedic["next_time"]

      this.isAddMouseDelay=true

      this.allKindArray=gradedic["marmot_num"]
    
      console.log("此时分类的地鼠数组",this.allKindArray)

      var  sortHoleArray=this.getRandomArrayElements(this.otherArray,gradedic["marmot_num"].length)

      for(var i=0;i<sortHoleArray.length;i++){
  
          this.addMouseLocation(sortHoleArray[i],i+this.lastAllmouse);
      }

      this.lastAllmouse=this.lastAllmouse+sortHoleArray.length

      console.log("已有地鼠数量",this.lastAllmouse)

    }
    else{

      console.log("已经没有多余洞口")

    }
   },

    stopGame:function(event, customEventData){

      this.stopView.active=true

      for(var i=0;i<this.mouseArray.length;i++){

        this.mouseArray[i].pauseAllActions();

      }

      this.timeshow.getComponent("timeShow").stopTime()

    
    },

    onAgainSence:function(){

      console.log("重新加载场景回调")
      this.startGameClick()
    
 
    },

    getUserInfoMessage:function(){

      var that= this
       httpUtils.NhttpPost("/marmot/user_info",{},function(res){

           console.log("用户信息",res)
           
           var stars =parseInt(res["ticket_num"])
           var energy=parseInt(res["energy_num"])
           that.numberCompontent.setText(stars)
           that.energyCompontent.setText(energy)

       })  
   },

    start(){

 
    },
  
    endGame:function(){

      for(var i=0;i<this.mouseArray.length;i++){

        this.mouseArray[i].pauseAllActions();

      }

    },

    startGame:function(){

    
      this.timeshow.getComponent("timeShow").startTime()

      for(var i=0;i<this.mouseArray.length;i++){

        this.mouseArray[i].resumeAllActions();

      }

    },

    addMouseLocation:function(numHole,currentMouseNum){

      //洞的随机口，第几只老鼠
      var  newhole= this.holeArray[numHole];
      
      var newmouse=  newhole.getComponent("hole").mouse

      newmouse.iconIndex=0

      var songNumber = Math.floor(Math.random()*3+0)

      newmouse.appearVoice=songNumber

      newmouse.clickVoice=songNumber

      // console.log("当前第几只地鼠",currentMouseNum);

      var categoryMouseArray=this.allKindArray[0]["category"]

        var arrayCount=categoryMouseArray.length

        var categoryNumber = Math.floor(Math.random()*arrayCount+0)

       var mousenum= categoryMouseArray[categoryNumber]
      
       if(mousenum==8){
        allVariableJs.waterMouseNsArray.push(newmouse.node)
       }


      newmouse.init(mousenum,numHole)

      if(this.mouseArray[currentMouseNum]){

        this.mouseArray.splice(currentMouseNum,1,newmouse.node)
        this.homeholeArray.splice(currentMouseNum,1,numHole)
        
      
      }else{

        this.mouseArray.push(newmouse.node)
        this.homeholeArray.push(numHole)

      }


      var timeArray= []

      for(var i=0;i<this.mouseArray.length-this.lastAllmouse;i++){
            
            timeArray.push(this.next_time*i)

      }

   
    
      var startdelay

      if(this.isAddMouseDelay){

    

        startdelay=cc.delayTime(timeArray[currentMouseNum-this.lastAllmouse]); 


      }else{

      
        startdelay=cc.delayTime(0);
      
      }
    

      var otherArray=this.getArrDifference(this.allHoleArrays,this.homeholeArray)

      this.otherArray=otherArray

      var mousepoint=newmouse.node.getPosition();
     
      var showAction = cc.show();

      var action = cc.moveTo(this.upTimes, mousepoint.x, mousepoint.y+180);

      var actionclose = cc.moveTo(this.downTimes, mousepoint.x, mousepoint.y);

      var delay = cc.delayTime(this.stayTimes);
      var basindelay = cc.delayTime(1);
      var disappear = cc.callFunc(function(){

    

        if(mousenum==8){

          var isEexitArray=allVariableJs.waterMouseNsArray.indexOf(newmouse.node)

          if(isEexitArray>-1){

           newmouse.node.pauseAllActions();
            let that = this
           cc.loader.loadRes("水盆", cc.SpriteFrame, function (err, spriteFrame) {
        
             newmouse.node.getComponent(cc.Sprite).spriteFrame = spriteFrame;

           });

         }else{

           console.log("水盆地鼠正常下去")
         
         }
        
        }

        }, this);

        var finish = cc.callFunc(function(){

         this.mouseArray[currentMouseNum].active=false

         this.isAddMouseDelay=false
     
        var numbergole=this.productRandNum()

        this.addMouseLocation(numbergole,currentMouseNum)

      }, this);

      if(mousenum==8){

        var seq = cc.sequence(startdelay,showAction,action, delay,disappear,basindelay, actionclose,finish);
        newmouse.node.runAction(seq);

      }else{

        var seq = cc.sequence(startdelay,showAction,action, delay, actionclose,finish);
        newmouse.node.runAction(seq);

      }

    },
    
    changeMouseLocation:function(numHole,currentMouseNum){

       //洞的随机口，第几只老鼠
        var  newhole= this.holeArray[numHole];
      
        var newmouse=  newhole.getComponent("hole").mouse

        newmouse.iconIndex=0

        var songNumber = Math.floor(Math.random()*3+0)

        newmouse.appearVoice=songNumber

        newmouse.clickVoice=songNumber

        var categoryMouseArray=this.allKindArray[0]["category"]

        var arrayCount=categoryMouseArray.length

        var categoryNumber = Math.floor(Math.random()*arrayCount+0)

        var mousenum=  categoryMouseArray[categoryNumber]

        if(mousenum==8){
          allVariableJs.waterMouseNsArray.push(newmouse.node)
        }

        newmouse.init(mousenum,numHole)

        if(this.mouseArray[currentMouseNum]){

          this.mouseArray.splice(currentMouseNum,1,newmouse.node)
          this.homeholeArray.splice(currentMouseNum,1,numHole)
          
        
        }else{

          this.mouseArray.push(newmouse.node)
          this.homeholeArray.push(numHole)

        }

        var otherArray=this.getArrDifference(this.allHoleArrays,this.homeholeArray)

        this.otherArray=otherArray

        var mousepoint=newmouse.node.getPosition();

        var timeArray= []

        for(var i=0;i<this.mouseArray.length;i++){
              
              timeArray.push(this.next_time*i)

        }
  
        var startdelay

        if(this.isDalyBool){
                
          startdelay=cc.delayTime(0); 

        }else{
          
          startdelay=cc.delayTime(0);
        
        }

        var showAction = cc.show();

        var action = cc.moveTo(this.upTimes, mousepoint.x, mousepoint.y+180);

        var actionclose = cc.moveTo(this.downTimes, mousepoint.x, mousepoint.y);

        var delay = cc.delayTime(this.stayTimes);

        var basindelay = cc.delayTime(1);

        var disappear = cc.callFunc(function(){


        if(mousenum==8){

          var isEexitArray=allVariableJs.waterMouseNsArray.indexOf(newmouse.node)

          if(isEexitArray>-1){

           newmouse.node.pauseAllActions();

            let that = this
           cc.loader.loadRes("水盆", cc.SpriteFrame, function (err, spriteFrame) {
       
             newmouse.node.getComponent(cc.Sprite).spriteFrame = spriteFrame;
           });

         }else{

           console.log("水盆地鼠正常下去")
         
         }   
        }

        }, this);
  
        var finish = cc.callFunc(function(){
 
           this.mouseArray[currentMouseNum].active=false

          this.isDalyBool=false
       
          var numbergole=this.productRandNum()
          
          this.changeMouseLocation(numbergole,currentMouseNum)

        }, this);

        if(mousenum==8){

          var seq = cc.sequence(startdelay,showAction,action, delay,disappear, basindelay,actionclose,finish);
          newmouse.node.runAction(seq);

        }else{

          var seq = cc.sequence(startdelay,showAction,action, delay, actionclose,finish);
          newmouse.node.runAction(seq);

        }
    },
     
     productRandNum:function(){

        var arrayCount=this.otherArray.length
        
        var num = Math.floor(Math.random()*arrayCount+0)

        var number=this.otherArray[num]

        return number

},

    signAnimates:function(kindnumber){

      var signnode=this.gameSigeDescJs.getComponent("gameSigeDesc").node

      this.gameSigeDescJs.getComponent("gameSigeDesc").init(kindnumber)

      signnode.active=true

      var action = cc.moveTo(1.5, signnode.x, signnode.y+150);

      var signnodefinish = cc.callFunc(function(){  
        signnode.active=false
        signnode.y=signnode.y-150
      

      }, this);

      var signseq=cc.sequence(action,signnodefinish);
      signnode.runAction(signseq)
      
    },

   endsignAnimates:function(kindnumber){


    var signnode=this.gameSigeDescJs.getComponent("gameSigeDesc").node

      this.gameSigeDescJs.getComponent("gameSigeDesc").init(kindnumber)


      signnode.active=true

      var action = cc.moveTo(1.5, signnode.x, signnode.y+150);
0
      var signnodefinish = cc.callFunc(function(){  

        signnode.active=false
        signnode.y=signnode.y-150
        allVariableJs.isUseHammer=false
        this.isClickChuzi=false
        this.isUseHammer=true
        this.hammerUserTime.active=false
        // this.spinChuiziNode.active=false
      
      }, this);

      var signseq=cc.sequence(action,signnodefinish);
      signnode.runAction(signseq)

   },

   showhurtAnimates:function(){

    this.signAnimates(0)
    this.hurtsprites.active=true
    this.hurtsprites.getComponent("hurtSprites").init()
    var delay = cc.delayTime(4);
    if(allVariableJs.isEnterEndTimes){
      this.hurtsprites.opacity =0
    }
    var finish = cc.callFunc(function(){
      this.hurtsprites.active=false
      console.log("伤害动画延迟4秒");
    }, this);
    var seq = cc.sequence(delay,finish);
    this.hurtsprites.runAction(seq)

  },

  //取出两个数组不同的元素
  getArrDifference(arr1, arr2) {
 
  return arr1.concat(arr2).filter(function(v, i, arr) {

      return arr.indexOf(v) === arr.lastIndexOf(v);

  });
},

  useChuiziClick:function(){
  
    if(this.isUseHammer&&allVariableJs.chuiziCount>0){

  
      this.hammerUserTime.getChildByName("hammerTimeLimit").getComponent("NumberView").setText(5)
      var interval = 1;
      // 重复次数
      var repeat =4;
      // 开始延时
      var delay = 0;

      var limitCount=5

      var that=this
      
      this.schedule(function(){

        limitCount=limitCount-1

        that.hammerUserTime.getChildByName("hammerTimeLimit").getComponent("NumberView").setText(limitCount)


      }, interval, repeat, delay);


      var changebig2 = cc.scaleTo(0.2,1.1);

      var finish = cc.callFunc(function(){
  
        var changesmail2 = cc.scaleTo(0.1,1.0);

        var _this=this
        var smailfinish=cc.callFunc(function(){

          _this.hammerUserTime.active=true
        })

        var seqs = cc.sequence(changesmail2,smailfinish)
        this.chuiziBtn.runAction(seqs)
     

     }, this);
  
     var seq = cc.sequence(changebig2,finish)
  
      this.chuiziBtn.runAction(seq)

  
    }
  
    if(allVariableJs.chuiziCount>0){
      
      if(this.isUseHammer){
      
        console.log("巨锤攻击开始")
        allVariableJs.isUseHammer=true
        allVariableJs.chuiziCount=allVariableJs.chuiziCount-1
        this.chuiziBtn.getChildByName("hammerPropShow").getChildByName("hammerPropLabel").getComponent("NumberView").setText(allVariableJs.chuiziCount)
        this.signAnimates(2)
        this.isClickChuzi=true
        this.scheduleOnce(function() {
         this.endsignAnimates(1)
        }, 5);
        this.isUseHammer=false
      
      }else{
  
        console.log("锤子效果还没消失不能使用");
      

      }
    }else{

      console.log("锤子道具数量不足");
      if(cc.isValid(this.showHubProjess)){
        this.showHubProjess.destroy();
      }
      this.showHubProjess = cc.instantiate(this.SvprogressPrefab);
      this.node.addChild(this.showHubProjess);
      this.showHubProjess.getComponent('SVProgressView').init("锤子道具不足")

       let finish = cc.callFunc(() => { 
      
        this.showHubProjess.destroy();
    
      }, this);
    let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(0.5), cc.fadeOut(1), finish);
    this.showHubProjess.runAction(action);
    }

   },

    update (dt) {

    },
});
